CC ?= gcc
SHARED := -fPIC --shared
SKYNET_PATH		?=3rd/skynet
BIN_PATH		?=bin
SKYNET_SRC_PATH ?= $(SKYNET_PATH)/skynet-src
LUA_CLIB_PATH	?= $(BIN_PATH)/luaclib
LUA_LIB_PATH	?= $(BIN_PATH)/lualib
CSERVICE_PATH	?= $(BIN_PATH)/cservice
SERVICE_PATH	?= $(BIN_PATH)/service


CFLAGS = -g -O0 -Wall -I$(LUA_INC) $(MYCFLAGS)
# CFLAGS += -DUSE_PTHREAD_LOCK

# lua

#lua库在skynet编译时已加载

LUA_INC ?= $(SKYNET_PATH)/3rd/lua

LUA_LIB	 ?= ext 

LUA_CLIB ?= protobuf cjson quicklz algorithm cjsonmysql cseri random aoi

all : \
  	$(foreach v, $(CSERVICE), $(CSERVICE_PATH)/$(v).so) \
  	$(foreach v, $(LUA_CLIB), $(LUA_CLIB_PATH)/$(v).so) \
  	LUA	\
  	SKYNET \
	MODULE


$(LUA_CLIB_PATH) :
	mkdir -p $(LUA_CLIB_PATH)

$(LUA_LIB_PATH) :
	mkdir $(LUA_LIB_PATH)

.PHONY:LUA
LUA:$(LUA_LIB_PATH)
	cp 3rd/pbc/binding/lua53/protobuf.lua $(LUA_LIB_PATH)

.PHONY:SKYNET
SKYNET:
	cd  $(SKYNET_PATH) && make linux
	cp $(SKYNET_PATH)/luaclib/* $(LUA_CLIB_PATH)
	cp -r $(SKYNET_PATH)/lualib/*  $(LUA_LIB_PATH) 
	cp -r $(SKYNET_PATH)/service  $(BIN_PATH) 
	cp -r $(SKYNET_PATH)/cservice  $(BIN_PATH) 
	cp  $(SKYNET_PATH)/skynet  $(BIN_PATH) 

.PHONY:MODULE
MODULE:
	for m in $(LUA_LIB); do cp -r $$m/* $(BIN_PATH); done  

define CSERVICE_TEMP
  $$(CSERVICE_PATH)/$(1).so : service-src/service_$(1).c | $$(CSERVICE_PATH)
	$$(CC) $$(CFLAGS) $$(SHARED) $$< -o $$@ -I$(SKYNET_SRC_PATH)
endef

$(foreach v, $(CSERVICE), $(eval $(call CSERVICE_TEMP,$(v))))

$(LUA_CLIB_PATH)/random.so : random/random.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -Irandom/ -I$(SKYNET_SRC_PATH) $^ -o $@ 

$(LUA_CLIB_PATH)/quicklz.so : quicklz/lua-quicklz.c quicklz/quicklz.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -Iquicklz/ -I$(SKYNET_SRC_PATH) $^ -o $@ 

$(LUA_CLIB_PATH)/algorithm.so : lua-algorithm/lua-algorithm.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -Ilua-algorithm/ -I$(SKYNET_SRC_PATH) $^ -o $@ 

$(LUA_CLIB_PATH)/protobuf.so : 3rd/pbc/binding/lua53/pbc-lua53.c | $(LUA_CLIB_PATH)
	cd 3rd/pbc && make lib
	$(CC) $(CFLAGS) $(SHARED) -I3rd/pbc/ -I$(SKYNET_SRC_PATH) $^ -o $@ ./3rd/pbc/build/libpbc.a

$(LUA_CLIB_PATH)/cjson.so : 3rd/lua-cjson/fpconv.c  3rd/lua-cjson/lua_cjson.c 3rd/lua-cjson/strbuf.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -I3rd/lua-cjson/ -I$(SKYNET_SRC_PATH) $^ -o $@

$(LUA_CLIB_PATH)/cjsonmysql.so : 3rd/lua-cjson-mysql/fpconv.c  3rd/lua-cjson-mysql/lua_cjson.c 3rd/lua-cjson-mysql/strbuf.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -I3rd/lua-cjson-mysql/ -I$(SKYNET_SRC_PATH) $^ -o $@

$(LUA_CLIB_PATH)/cseri.so : 3rd/lua-serialize/fpconv.c  3rd/lua-serialize/lua_cjson.c 3rd/lua-serialize/strbuf.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -I3rd/lua-serialize/ -I$(SKYNET_SRC_PATH) $^ -o $@

$(LUA_CLIB_PATH)/aoi.so : aoi/lua-aoi.c aoi/aoi.c | $(LUA_CLIB_PATH)
	$(CC) $(CFLAGS) $(SHARED) -Iaoi/ -I$(SKYNET_SRC_PATH) $^ -o $@ 

clean :
	rm -rf $(BIN_PATH)/*

echo:
	echo $(LUA_INC)

cleanall: clean

